import React from 'react';
import { Modal,Checkbox,Spin } from 'antd';
import { doRobotList } from '@/services/robotManagement';

class AddRobotAnswer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      visible:false,
      loadingRobotList:false,
      robotList:[],
      checkedValues:[],
      disabledValues:[]
    }
  }

  componentDidMount() {
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  cancelModal = () => {
    this.setState({
      visible:false
    })
  }

  /**
   * 初始化
   * @returns {*}
   */
  initModal = (robotAnswers) => {
    //将已选择的机器人作选中状态 且不能修改
    const checkedValues = robotAnswers.map(item => item.robotId);
    this.setState({
      visible:true,
      checkedValues,
      disabledValues:checkedValues
    },() => {
      this.getRobotList();
    })
  }

  /**
   * 获取所有机器人
   * @returns {*}
   */
  getRobotList = () => {
    this.setState({
      loadingRobotList:true
    },async () => {
      const res = await doRobotList({current:1,size:999999})
      this.setState({
        robotList:res ? res : [],
        loadingRobotList:false
      })
    })
  }

  /**
   * 选择机器人
   * @returns {*}
   */
  changeRobot = (checkedValues) => {
    this.setState({
      checkedValues
    })
  }

  /**
   * 确定
   * @returns {*}
   */
  getCheckRobot = () => {
    const { checkedValues,robotList } = this.state;
    this.props.addRobotAnswers(checkedValues,robotList)
  }

  render() {
    const { visible,loadingRobotList,robotList,checkedValues,disabledValues } = this.state;
    return (
      <Modal
        title={'添加应用答案'}
        visible={visible}
        onCancel={this.cancelModal}
        onOk={this.getCheckRobot}
      >
        <div style={{marginBottom:10}}>请选择要添加的应用：</div>
        <div>
          <Spin spinning={loadingRobotList}>
            <Checkbox.Group style={{ width: '100%' }} value={checkedValues} onChange={this.changeRobot}>
              {
                robotList.map(item => {
                  return (
                    <Checkbox value={item.id} key={item.id} disabled={disabledValues.indexOf(item.id) != -1}>
                      {item.name}
                      {disabledValues.indexOf(item.id) != -1 ? '（已添加）' : ''}
                    </Checkbox>
                  )
                })
              }
            </Checkbox.Group>
          </Spin>
        </div>
      </Modal>
    );
  }
}

export default AddRobotAnswer;
